package source

import (
	"errors"
	"fmt"

	"github.com/PuerkitoBio/goquery"
)

const tbbaseUrl = "https://tieba.baidu.com"

type Tieba struct {
	baseUrl string
}

func init() {
	registerType((*Tieba)(nil))
}

//get movie cover images url
func (J Tieba) FetchNews(url string) ([]NEWS, error) {
	println("query url :" + url)
	var newslist []NEWS
	pageDoc, err := goquery.NewDocument(url)
	if err != nil {
		fmt.Println(err)
		return newslist, err
	}

	rootnode := pageDoc.Find("#thread_list")
	if len(rootnode.Nodes) <= 0 {
		return newslist, errors.New("can't find table")
	}
	fmt.Printf("news count: %d \n", len(rootnode.First().Find("li.j_thread_list").Nodes))
	rootnode.First().Find("li.j_thread_list").Each(func(i int, tr *goquery.Selection) {
		topnode := tr.Find("i.icon-top").First()
		if len(topnode.Nodes)>0 {
			return
		}
		node := tr.Find("a.j_th_tit").First()

		item := NEWS{}
		if href, b := node.Attr("href"); b == true {
			item.Url = tbbaseUrl + href
			item.Title = node.Text()
		} else {
			// fmt.Println(tr.Attr("id"))
			return
		}
		timenode := tr.Find("td.by em").First()
		if len(timenode.Nodes) > 0 {
			item.Time = timenode.Text()
		}
		authornode := tr.Find("div.threadlist_author span.tb_icon_author").First()
		if title, b := authornode.Attr("title"); b == true {
			item.Author = title
		}
		newslist = append(newslist, item)

	})

	return newslist, nil
}
